package com.kaifamiao.month05.day10.test;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("服务器启动……");
        ThreadPoolExecutor receivePool = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        ThreadPoolExecutor SendPool = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        while (true) {
            Socket accept = server.accept();
            receivePool.execute(new ReceiveThread(accept));
            SendPool.execute(new SendThread(accept,ReceiveThread.getMap()));
        }
    }
}
// 接收消息的进程
class ReceiveThread implements Runnable {

    private static HashMap<Socket,String> map = new HashMap<>();

    private Socket accept;

    public static HashMap<Socket, String> getMap() {
        return map;
    }

    public ReceiveThread(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        try {
            byte[] bs = accept.getInputStream().readAllBytes();
            System.out.println(new String(bs));
            if (bs.length > 36) {
                String mess = new String(bs);
                map.put(accept, mess);
                System.out.println("你输入的内容：" + mess);
            } else {
                map.put(accept, null);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

//发送消息的进程
class SendThread implements Runnable {

    private HashMap<Socket,String> map = new HashMap<>();

    private Socket accept;

    public SendThread(Socket accept,HashMap<Socket,String> map) {
        this.accept = accept;
        this.map = map;
    }

    @Override
    public void run() {
        try {
            OutputStream out = accept.getOutputStream();
            String message = null;
            for (String mess : map.values()) {
                if (mess != null) {
                    message = mess;
                }
            }

            for (String mess : map.values()) {
                if (mess != null) {
                    out.write("消息发送成功！".getBytes());
                } else {
                    out.write(message.getBytes());
                }
            }
            accept.shutdownOutput();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
